<template>
	<view class="confirm-container">
		<!-- 行程信息卡片 -->
		<view class="travel-card">
			<!-- 行程名称 -->
			<view class="tour-name">{{ travelInfo.name }}</view>
			<view class="travel-info">
				<view class="travel-label">套餐名称</view>
				<view class="travel-field">
					{{ getSkuName(tourInfo) }}
				</view>
			</view>

			<!-- 出行日期和地点 -->
			<view class="travel-info">
				<view class="travel-label">出行时间</view>
				<view class="travel-dates travel-field">
					{{ formatDate(stockInfo.travel_date, 'YYYY年MM月DD日') }}
				</view>
				<view v-if="travelInfo.departure_city" class="travel-field" style="padding-left: 12rpx;">
					{{  travelInfo.departure_city }}出发
				</view>
			</view>

			<view class="travel-info">
				<view class="travel-label">购买须知</view>
				<view>
					<text class="travel-field">需商家确认</text>
					<text class="travel-dates" style="padding-left: 12rpx;">
						{{ refundDate }}前可免费退订
					</text>
				</view>
				<view class="travel-field-more" @click="openNotice">
					详情 >
				</view>
			</view>
		</view>

		<!-- 出行人信息填写区域 -->
		<view class="traveler-info-card">
			<!-- 标题和说明 -->
			<view class="info-header">
				<view class="info-title">选择出行人数</view>
				<view class="info-instruction">须按出游所持证件信息填写</view>
			</view>

			<!-- 出行人选择区域 -->
			<view class="traveler-selection">
				<view class="traveler-cards">
					<view v-for="(traveler, index) in travelers" :key="index"
						:class="['traveler-card', { 'selected': traveler.selected, 'child': traveler.type === 'child' }]"
						@click="selectTraveler(index)">
						<view v-if="traveler.type === 'child'" class="traveler-type">儿童</view>
						<view class="traveler-name">{{ traveler.name }}</view>
					</view>
					<view class="traveler-card add-card" @click="showAddTraveler">
						<view class="add-text">新增/选择</view>
					</view>
				</view>
			</view>

			<!-- 出行人详细信息 -->
			<view class="traveler-details">
				<view v-for="(traveler, index) in selectedTravelers" :key="index" class="traveler-detail-item">
					<view class="detail-left">
						<view class="remove-btn" @click="removeTraveler(traveler.id)">Θ</view>
						<view class="traveler-info">
							<view class="detail-name">
								{{ traveler.name }}
								<view class="traveler-tag">{{ traveler.type === 'adult' ? '成人' : '儿童' }}</view>
							</view>
							<view class="id-info">身份证 {{ maskIdCard(traveler.id_card) }}</view>
						</view>
					</view>
					<view class="edit-btn" @click="showEditTraveler(traveler.id)">✏️</view>
				</view>
			</view>
		</view>

		<!-- 房间选择区域 -->
		<view class="room-selection-card" v-if="stockInfo.single_price_diff">
			<view class="info-header">
				<view class="info-title">单房差</view>
			</view>

			<view class="room-selection">
				<view class="room-price-info">
					<view class="price-label">单价：</view>
					<view class="price-value">¥{{ stockInfo.single_price_diff }}</view>
				</view>
				<view class="room-info">
					<view class="room-count-control">
						<u-number-box v-model="roomCount" :min="0" :max="maxRoomCount" :step="1"></u-number-box>
					</view>
				</view>
			</view>
		</view>

		<!-- 酒店选择区域 -->
		<view class="hotel-selection-card" v-if="hotelLevels && hotelLevels.length > 0">
			<view class="info-header">
				<view class="info-title">酒店选择</view>
			</view>

			<view class="hotel-selection">
				<view class="hotel-options">
					<view 
						v-for="(hotel, index) in hotelLevels" 
						:key="index"
						:class="['hotel-option', { 'selected': selectedHotelIndex === index }]"
						@click="selectHotel(index)">
						<view class="hotel-info">
							<view class="hotel-name">{{ hotel.level_name }}</view>
							<view class="hotel-description" v-if="hotel.description">{{ hotel.description }}</view>
						</view>
						<view class="hotel-price">¥{{ hotel.price }}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 联系人信息填写区域 -->
		<view class="contact-card">
			<view class="contact-header">
				<view class="contact-title">
					<text>联系人</text>
					<text class="contact-title-more">商家将与您确认行程信息</text>
				</view>
			</view>
			<view class="contact-content">
				<view class="contact-item">
					<view class="contact-label">姓名</view>
					<input class="contact-input" v-model="contactForm.name" placeholder="请输入联系人姓名" maxlength="10" />
				</view>
				<view class="contact-item">
					<view class="contact-label">手机号</view>
					<input class="contact-input" v-model="contactForm.phone" placeholder="请输入手机号码" maxlength="11"
						type="number" />
				</view>
				<view class="contact-item">
					<view class="contact-label">其他信息</view>
					<input class="contact-input" v-model="remarkText" placeholder="请输入备注信息" type="textarea" />
				</view>
			</view>
		</view>

		<!-- 出行人表单弹窗 -->
		<u-popup v-model="showTravelerForm" mode="bottom" border-radius="20">
			<view class="traveler-form">
				<view class="form-header">
					<view class="form-title">{{ isEdit ? '编辑出行人' : '新增出行人' }}</view>
					<view class="close-btn" @click="closeTravelerForm">×</view>
				</view>

				<view class="form-content">
					<view class="form-item">
						<view class="form-label">姓名</view>
						<input class="form-input" v-model="travelerForm.name" placeholder="请输入姓名" maxlength="5" />
					</view>

					<view class="form-item">
						<view class="form-label">身份证号码</view>
						<input class="form-input" v-model="travelerForm.id_card" placeholder="请输入身份证号码" maxlength="18"
							@input="onIdCardInput" />
					</view>

					<view class="form-item">
						<view class="form-label">性别</view>
						<view class="form-value">{{ travelerForm.gender || '请先输入身份证号码' }}</view>
					</view>

					<view class="form-item">
						<view class="form-label">出生日期</view>
						<view class="form-value">{{ travelerForm.birth_date || '请先输入身份证号码' }}</view>
					</view>
					<view class="form-item">
						<view class="form-label">联系方式</view>
						<input class="form-input" v-model="travelerForm.phone" placeholder="请输入手机号码" maxlength="11"
							type="number" />
					</view>
				</view>

				<view class="form-actions">
					<view style="flex: 1;"">
						<ZButton type="secondary" @click="closeTravelerForm">取消</ZButton>
					</view>
					<view style="flex: 1;">
						<ZButton type="primary" @click="saveTraveler">保存</ZButton>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 购买须知弹窗 -->
		<u-popup v-model="showNotice" mode="bottom" border-radius="20">
			<view class="notice-popup">
				<view class="notice-header">
					<view class="notice-title">购买须知</view>
					<view class="close-btn" @click="closeNotice">×</view>
				</view>
				<scroll-view class="notice-content" scroll-y="true">
					<view class="notice-content-item">
						<rich-text :nodes="travelInfo.booking_notice"></rich-text>
					</view>
				</scroll-view>
			</view>
		</u-popup>

		<!-- 价格明细弹窗 -->
		<u-popup v-model="showPriceDetail" mode="bottom" border-radius="20">
			<view class="price-detail">
				<view class="detail-header">
					<view class="detail-title">金额明细</view>
					<view class="close-btn" @click="closePriceDetail">×</view>
				</view>
				<view class="detail-content">
					<view class="detail-item" v-if="adultCount > 0">
						<view class="detail-label">成人票</view>
						<view class="detail-value">¥{{ stockInfo.adult_price || 0 }} × {{ adultCount }}</view>
					</view>
					<view class="detail-item" v-if="childCount > 0">
						<view class="detail-label">儿童票</view>
						<view class="detail-value">¥{{ stockInfo.child_price || 0 }} × {{ childCount }}</view>
					</view>
					<view class="detail-item" v-if="stockInfo.single_price_diff && roomCount > 0">
						<view class="detail-label">单房差</view>
						<view class="detail-value">¥{{ stockInfo.single_price_diff }} × {{ roomCount }}</view>
					</view>
					<view class="detail-item" v-if="getSelectedHotel()">
						<view class="detail-label">酒店费用</view>
						<view class="detail-value">¥{{ getSelectedHotel().price }} × {{ selectedTravelers.length }}</view>
					</view>
					<view class="detail-divider"
						v-if="adultCount > 0 || childCount > 0 || (stockInfo.single_price_diff && roomCount > 0) || getSelectedHotel()">
					</view>
					<view class="detail-item total">
						<view class="detail-label">小计</view>
						<view class="detail-value">¥{{ (parseFloat(subtotal) +
							parseFloat(singleRoomDiffAmount) + parseFloat(hotelAmount)).toFixed(2) }}</view>
					</view>
					<view class="detail-item discount" v-if="discountAmount > 0">
						<view class="detail-label">优惠券</view>
						<view class="detail-value">-¥{{ discountAmount }}</view>
					</view>
					
					<view class="detail-item discount" v-if="shareOrder.prepay_amount">
						<view class="detail-label">预付优惠</view>
						<view class="detail-value">-¥{{ shareOrder.prepay_amount }}</view>
					</view>
					<view class="detail-item final">
						<view class="detail-label">实付金额</view>
						<view class="detail-value">¥{{ finalAmount }}</view>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 底部固定栏 -->
		<view class="bottom-bar">
			<view class="login-footer">
				<view class="check" style="display: flex;align-items: center">
					<div style="display: flex;align-items: center" @click="setAgree()">
						<image v-if="agree" class="publish-icon" src="/static/radio_fill.png"></image>
						<image v-else class="publish-icon" src="/static/radio.png"></image>
						<text style="color: #8F959E;font-size: 28rpx">我已阅读并同意</text>
					</div>
					<text style="color: #E68627" @click="setAgree2('travel_sale_user_agreement')">《旅行销用户须知》</text>
					<text style="color: #8F959E;font-size: 28rpx">及</text>
					<text style="color: #E68627" @click="setAgree2('travel_contract')">《旅游合同条款》</text>
				</view>
			</view>
			<view class="submit-btn-box">

				<view class="price-summary">
					<view class="total-price">
						<text class="currency">¥</text>
						<text class="amount">{{ totalPrice }}</text>
						<!-- <view class="discount-tag">共优惠 ¥{{ discountAmount }}</view> -->
					</view>
					<view class="price-label">订单总额</view>
				</view>
				<view class="action-buttons">
					<view class="detail-btn" @click="openShowPriceDetail">
						<text>明细</text>
						<text class="chevron">▼</text>
					</view>
					<ZButton style="width: 200rpx;" color="#ff6b35" class="submit-btn" @click="submitOrder"
						:disabled="loading">
						<text>{{ loading ? '提交中...' : '立即支付' }}</text>
					</ZButton>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import ZButton from '@/components/ZButton.vue'
import dayjs from 'dayjs'
export default {
	components: {
		ZButton
	},
	data() {
		return {
			shareOrder: {},
			travelInfo: {},
			tourInfo: {
			},
			stockInfo: {
			},
			contactForm: {
				name: '',
				phone: ''
			}, // 联系人信息
			remarkText: '', // 备注文本
			travelers: [], // 从接口获取出行人列表
			showTravelerForm: false,
			showPriceDetail: false,
			showNotice: false,
			isEdit: false,
			editingId: null,
			travelerForm: {
				name: '',
				id_card: '', // 改为下划线格式
				gender: '',
				birth_date: '', // 改为下划线格式
				phone: ''
			},
			discountAmount: 0,
			loading: false,
			skuId: '',
			travelId: '',
			skuDateId: '',
			roomCount: 0, // 房间数量，默认为0（不需要补单房差）
			maxRoomCount: 1, // 最大房间数量
			agree: false,
			hotelLevels: [], // 酒店级别列表
			selectedHotelIndex: -1 // 选中的酒店级别索引
		}
	},
	computed: {
		// 出发日期前3天免费退订
		refundDate() {
			// this.stockInfo.travel_date - 3使用dayjs
			return dayjs(this.stockInfo.travel_date).subtract(3, 'day').format('MM月DD日 18:00');
		},
		selectedTravelers() {
			return this.travelers.filter(traveler => traveler.selected);
		},
		// 成人数量
		adultCount() {
			return this.selectedTravelers.filter(traveler => traveler.type === 'adult').length;
		},
		// 儿童数量
		childCount() {
			return this.selectedTravelers.filter(traveler => traveler.type === 'child').length;
		},
		// 小计金额
		subtotal() {
			const adultTotal = this.adultCount * (this.stockInfo.adult_price || 0);
			const childTotal = this.childCount * (this.stockInfo.child_price || 0);
			return (adultTotal + childTotal).toFixed(2);
		},
		// 单房差金额
		singleRoomDiffAmount() {
			if (this.stockInfo.single_price_diff && this.roomCount > 0) {
				return (this.stockInfo.single_price_diff * this.roomCount).toFixed(2);
			}
			return '0.00';
		},
		// 酒店费用金额
		hotelAmount() {
			const selectedHotel = this.getSelectedHotel();
			if (selectedHotel && this.selectedTravelers.length > 0) {
				return (selectedHotel.price * this.selectedTravelers.length).toFixed(2);
			}
			return '0.00';
		},
		// 最终金额
		finalAmount() {
			const subtotal = parseFloat(this.subtotal);
			const singleRoomDiff = parseFloat(this.singleRoomDiffAmount);
			const discount = this.discountAmount;
			const totalBeforePrepay = subtotal + singleRoomDiff + parseFloat(this.hotelAmount) - discount;
			
			// 只有当总金额大于0时，才应用预付优惠
			if (totalBeforePrepay > 0) {
				const prepayDiscount = parseFloat(this.shareOrder.prepay_amount || 0);
				const finalAmount = totalBeforePrepay - prepayDiscount;
				// 如果计算结果小于0，则默认为0
				return Math.max(0, finalAmount).toFixed(2);
			} else {
				return '0.00';
			}
		},
		// 总价（用于底部显示）
		totalPrice() {
			return this.finalAmount;
		}
	},

	watch: {
		// 监听选择的出行人变化，更新最大房间数量
		selectedTravelers: {
			handler(newVal) {
				if (this.stockInfo.single_price_diff) {
					this.maxRoomCount = this.calculateMaxRoomCount();
					// 如果当前房间数量超过最大数量，调整为最大数量
					if (this.roomCount > this.maxRoomCount) {
						this.roomCount = this.maxRoomCount;
					}
					// 如果没有出行人，房间数量设为0
					if (totalTravelers === 0) {
						this.roomCount = 0;
					}
				}
			},
			deep: true
		}
	},

	onLoad(options) {
		console.log(options, '代付的订单');
		if (options.id) {
			this.shareOrderId = options.id
			
		}
	},
	onShow() {
		// 如果用户未登录，跳转到登录页
		if (!this.userInfo.id) {
			uni.showModal({
				title: '提示',
				content: '请先登录',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}
				}
			});
			return;
		}
		if (this.shareOrderId) {
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					this.$api.getTravelShareOrderDetail(this.shareOrderId).then(res => {
						uni.hideLoading();
						console.log(res)
						this.skuId = res.travel_sku_id
						this.travelId = res.travel_id
						this.skuDateId = res.travel_sku_stock_id
						if (res.user_id) {
							// 连接已生效
							uni.showToast({
								title: '链接已失效',
								icon: 'success'
							});
							setTimeout(() => {
								this.$goPage({
									url: '/pages/index/index',
									switchTab: true
								})
							}, 1000)
						} else {
							this.shareOrder = res
							this.initData()
						}
						const parentUserId = res.distributor_id
						if (parentUserId && this.userInfo.id && this.userInfo.id !== parentUserId && !this.userInfo.parent_user_id) {
							this.$api.updateUser(this.userInfo.id, {
								parent_user_id: parentUserId
							})
						}
					})
				} else {
					this.$goPage({
						url: '/pages/index/index',
						switchTab: true
					})
				}
	},
	methods: {
		initData() {
			// 如果用户已登录且有ID，重新加载出行人列表
			this.loadTravelers();
			this.$api.getTravelSkuStock(this.skuDateId).then(res => {
				console.log(res)
				this.stockInfo = res
				// 初始化房间数量
				this.roomCount = 0;
				this.maxRoomCount = this.calculateMaxRoomCount();
			})
			this.$api.getTravelDetail(this.travelId).then(res => {
				console.log(res)
				this.travelInfo = res
				

				this.$api.getTravelSkuDetail(this.skuId).then(res2 => {
					console.log(res2)
					this.tourInfo = res2
				})
			})
		},
		// 获取SKU名称
		getSkuName(sku) {
			console.log('sku', sku);
			if (!sku || !sku.spec_combination) return '';

			try {
				const specCombination = JSON.parse(sku.spec_combination);
				const specNames = Object.values(specCombination).map(value => value.replace(/,/g, '|'));
				return specNames.join(' | ');
			} catch (error) {
				console.error('解析SKU规格失败:', error);
				return '';
			}
		},
		setAgree() {
			this.agree = !this.agree;
		},
		selectTraveler(index) {
			this.travelers[index].selected = !this.travelers[index].selected;
		},
		showAddTraveler() {
			this.isEdit = false;
			this.editingId = null;
			this.resetTravelerForm();
			this.showTravelerForm = true;
		},
		showEditTraveler(id) {
			this.isEdit = true;
			this.editingId = id;
			const traveler = this.travelers.find(t => t.id === id);
			if (traveler) {
				// 编辑时显示完整的身份证号码
				this.travelerForm = {
					name: traveler.name,
					id_card: traveler.id_card, // 显示完整身份证号码
					gender: traveler.gender,
					birth_date: traveler.birth_date || '',
					phone: traveler.phone
				};
			}
			this.showTravelerForm = true;
		},
		closeTravelerForm() {
			this.showTravelerForm = false;
			this.resetTravelerForm();
		},
		resetTravelerForm() {
			this.travelerForm = {
				name: '',
				id_card: '',
				gender: '',
				birth_date: '',
				phone: ''
			};
		},
		onIdCardInput() {
			// 根据身份证号码获取性别和出生日期
			if (this.travelerForm.id_card.length === 18) {
				// 验证身份证格式
				if (this.validateIdCard(this.travelerForm.id_card)) {
					const genderCode = parseInt(this.travelerForm.id_card.charAt(16));
					this.travelerForm.gender = genderCode % 2 === 1 ? '男' : '女';

					// 解析出生日期
					const year = this.travelerForm.id_card.substring(6, 10);
					const month = this.travelerForm.id_card.substring(10, 12);
					const day = this.travelerForm.id_card.substring(12, 14);
					this.travelerForm.birth_date = `${year}-${month}-${day}`;
				} else {
					this.travelerForm.gender = '';
					this.travelerForm.birth_date = '';
					uni.showToast({
						title: '身份证号码格式不正确',
						icon: 'none'
					});
				}
			} else {
				this.travelerForm.gender = '';
				this.travelerForm.birth_date = '';
			}
		},

		// 验证身份证号码
		validateIdCard(idCard) {
			return true
			// 身份证号码正则表达式
			const idCardReg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;

			if (!idCardReg.test(idCard)) {
				return false;
			}

			// 验证校验码
			const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
			const parity = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
			let sum = 0;
			let ai = 0;
			let wi = 0;

			for (let i = 0; i < 17; i++) {
				ai = idCard[i];
				wi = factor[i];
				sum += ai * wi;
			}

			const last = parity[sum % 11];
			if (last !== idCard[17].toUpperCase()) {
				return false;
			}

			return true;
		},

		// 验证手机号
		validatePhone(phone) {
			const phoneReg = /^1[3-9]\d{9}$/;
			return phoneReg.test(phone);
		},

		// 身份证号码脱敏
		maskIdCard(idCard) {
			if (!idCard || idCard.length < 8) {
				return idCard;
			}
			// 保留前4位和后4位，中间用*替换
			return idCard.substring(0, 4) + '*'.repeat(idCard.length - 8) + idCard.substring(idCard.length - 4);
		},
		saveTraveler() {
			// 表单验证
			if (!this.travelerForm.name.trim()) {
				uni.showToast({
					title: '请输入姓名',
					icon: 'none'
				});
				return;
			}
			if (this.travelerForm.name.trim().length > 5) {
				uni.showToast({
					title: '姓名不能超过5位',
					icon: 'none'
				});
				return;
			}
			if (!this.travelerForm.id_card.trim()) {
				uni.showToast({
					title: '请输入身份证号码',
					icon: 'none'
				});
				return;
			}
			if (!this.validateIdCard(this.travelerForm.id_card)) {
				uni.showToast({
					title: '身份证号码格式不正确',
					icon: 'none'
				});
				return;
			}
			if (!this.travelerForm.phone.trim()) {
				uni.showToast({
					title: '请输入联系方式',
					icon: 'none'
				});
				return;
			}
			if (!this.validatePhone(this.travelerForm.phone)) {
				uni.showToast({
					title: '手机号码格式不正确',
					icon: 'none'
				});
				return;
			}

			// 构建出行人数据
			const travelerData = {
				name: this.travelerForm.name,
				id_card: this.travelerForm.id_card,
				birth_date: this.travelerForm.birth_date,
				phone: this.travelerForm.phone,
				user_id: this.userInfo.id
			};

			if (this.isEdit) {
				// 编辑模式
				this.$api.updateTraveler(this.editingId, travelerData).then(res => {
					this.closeTravelerForm();
					this.loadTravelers(); // 重新加载出行人列表
					uni.showToast({
						title: '编辑成功',
						icon: 'success'
					});
				}).catch(error => {
					console.error('编辑出行人失败:', error);
					uni.showToast({
						title: '编辑失败，请重试',
						icon: 'none'
					});
				});
			} else {
				// 新增模式
				this.$api.createTraveler(travelerData).then(res => {
					this.closeTravelerForm();
					this.loadTravelers(); // 重新加载出行人列表
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
				}).catch(error => {
					console.error('添加出行人失败:', error);
					uni.showToast({
						title: '添加失败，请重试',
						icon: 'none'
					});
				});
			}
		},
		// 加载出行人列表
		loadTravelers() {
			if (!this.userInfo.id) {
				return;
			}

			this.$api.getTravelerList({ user_id: this.userInfo.id }).then(res => {
				// 处理出行人数据，添加type和selected字段
				this.travelers = res.map(traveler => {
					// 根据出生日期计算年龄，确定是成人还是儿童
					const birthYear = new Date(traveler.birth_date).getFullYear();
					const currentYear = new Date().getFullYear();
					const age = currentYear - birthYear;
					const type = age >= 18 ? 'adult' : 'child';

					// 根据身份证号码获取性别
					const genderCode = parseInt(traveler.id_card.charAt(16));
					const gender = genderCode % 2 === 1 ? '男' : '女';

					return {
						...traveler,
						type,
						gender,
						selected: false // 默认不选中
					};
				});
			}).catch(error => {
				console.error('加载出行人列表失败:', error);
			});
		},
		removeTraveler(id) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个出行人吗？',
				success: (res) => {
					if (res.confirm) {
						this.$api.deleteTraveler(id).then(res => {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							this.loadTravelers(); // 重新加载出行人列表
						}).catch(error => {
							console.error('删除出行人失败:', error);
							uni.showToast({
								title: '删除失败，请重试',
								icon: 'none'
							});
						});
					}
				}
			});
		},

		// 价格明细相关方法
		openShowPriceDetail() {
			this.showPriceDetail = true;
		},

		closePriceDetail() {
			this.showPriceDetail = false;
		},
		// 计算最大房间数量
		calculateMaxRoomCount() {
			if (!this.stockInfo.single_price_diff) {
				return 0;
			}
			// 根据选择的出行人数量计算最大房间数
			const totalTravelers = this.selectedTravelers.length;
			if (totalTravelers === 0) {
				return 0;
			}
			// 最大房间数不能超过每人一间
			return totalTravelers;
		},

		submitOrder() {
			// 防止重复提交
			if (this.loading) {
				return;
			}
			if (!this.agree) {
				uni.showToast({
					title: '请先阅读并同意用户须知',
					icon: 'none'
				});
				return;
			}
			// 检查用户是否已登录
			if (!this.userInfo.id) {
				uni.showModal({
					title: '提示',
					content: '请先登录',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/login'
							});
						}
					}
				});
				return;
			}

			// 验证必填项
			if (this.selectedTravelers.length === 0) {
				uni.showToast({
					title: '请至少选择一位出行人',
					icon: 'none'
				});
				return;
			}

			// 构建旅游订单数据
			const orderData = {
				user_id: this.userInfo.id,
				prepay_amount: this.shareOrder.prepay_amount || 0, // 预付优惠金额
				travel_share_order_id: this.shareOrder.id || 0,
				travel_id: this.travelId, // 旅游产品ID
				travel_sku_id: this.skuId, // 旅游产品SKU ID
				travel_sku_stock_id: this.stockInfo.id, // 旅游产品SKU库存ID
				travel_date: this.stockInfo.travel_date, // 出行日期
				adult_count: this.adultCount, // 成人数量
				child_count: this.childCount, // 儿童数量
				adult_price: this.stockInfo.adult_price, // 成人价格
				child_price: this.stockInfo.child_price, // 儿童价格
				room_count: this.roomCount, // 房间数量
				single_price_diff: this.stockInfo.single_price_diff || 0, // 单房差价格
				single_room_diff_amount: this.singleRoomDiffAmount, // 单房差总金额
				// 新增酒店级别相关字段
				hotel_level_name: this.getSelectedHotel() ? this.getSelectedHotel().level_name : '', // 酒店级别名称
				hotel_level_price: this.getSelectedHotel() ? this.getSelectedHotel().price : 0.00, // 酒店级别价格
				hotel_level_count: this.selectedTravelers.length, // 酒店级别数量（出行人总数）
				hotel_level_amount: this.hotelAmount, // 酒店级别总价
				payment_amount: this.finalAmount, // 总金额
				discount_amount: this.discountAmount, // 优惠金额
				travelers: JSON.stringify(this.selectedTravelers), // 出行人信息
				contact_name: this.contactForm.name, // 联系人姓名
				contact_phone: this.contactForm.phone, // 联系人手机号
				remark: this.remarkText, // 备注信息
				order_type: 'travel' // 订单类型：旅游
			};

			this.loading = true;
			uni.showLoading({
				title: '提交中...'
			});

			// 提交旅游订单
			this.$api.createTravelOrder(orderData).then(res => {
				uni.hideLoading();
				this.loading = false;
				uni.showToast({
					title: '订单提交成功',
					icon: 'success'
				});
				// 如果订单状态为待支付，则进行支付
				if (res.status === 'pending') {
					this.getPay(res.id)
				} else {
					uni.redirectTo({
						url: "/pages/travelOrder/travelOrder"
					})
				}
			}).catch(error => {
				uni.hideLoading();
				this.loading = false;
				console.error('提交旅游订单失败:', error);
				uni.showToast({
					title: '提交失败，请重试',
					icon: 'none'
				});
			});
		},

		getPay(order_id) {
			uni.showLoading({
				title: '微信支付请求'
			});
			const that = this
			this.$api.createTravelOrderPay({
				order_id
			}).then(payment => {
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: payment.timestamp,
					nonceStr: payment.nonce_str,
					package: payment.package,
					signType: payment.signType,
					paySign: payment.paySign,
					success: (result) => {
						uni.showToast({
							title: '支付成功'
						});
					},
					fail: (result) => {
						uni.showToast({
							icon: 'none',
							title: '支付失败',
						});
					},
					complete: () => {
						setTimeout(() => {
							uni.redirectTo({
								url: "/pages/travelOrder/travelOrder?orderId=" + order_id
							})
						}, 1000);
					}
				});
			}).catch(res => {
				this.loading = false;
				setTimeout(() => {
					uni.redirectTo({
						url: "/pages/travelOrder/travelOrder?orderId=" + order_id
					})
				}, 1000);
			})
		},
		openNotice() {
			this.showNotice = true;
		},

		closeNotice() {
			this.showNotice = false;
		},
		// 选择酒店级别
		selectHotel(index) {
			this.selectedHotelIndex = index;
		},
		// 获取选中的酒店级别
		getSelectedHotel() {
			if (this.selectedHotelIndex >= 0 && this.hotelLevels[this.selectedHotelIndex]) {
				return this.hotelLevels[this.selectedHotelIndex];
			}
			return null;
		},
		// 解析酒店级别数据
		parseHotelLevels() {
			if (this.stockInfo.hotel_levels) {
				try {
					const parsed = JSON.parse(this.stockInfo.hotel_levels);
					if (Array.isArray(parsed) && parsed.length > 0) {
						// 根据sort字段排序
						this.hotelLevels = parsed.sort((a, b) => (a.sort || 0) - (b.sort || 0));
						// 默认选择第一个酒店级别
						this.selectedHotelIndex = 0;
					} else {
						this.hotelLevels = [];
						this.selectedHotelIndex = -1;
					}
				} catch (error) {
					console.error('解析酒店级别数据失败:', error);
					this.hotelLevels = [];
					this.selectedHotelIndex = -1;
				}
			} else {
				this.hotelLevels = [];
				this.selectedHotelIndex = -1;
			}
		}
	}
}
</script>

<style scoped lang="scss">
.confirm-container {
	padding: 20rpx;
	padding-bottom: 220rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.travel-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;

	.travel-info {
		display: flex;
		align-items: center;
		padding: 4rpx 0;

		.travel-field-more {
			flex-grow: 1;
			text-align: right;
			font-size: 24rpx;
			color: #333
		}

		.travel-label {
			font-size: 24rpx;
			color: #333333;
			padding-right: 20rpx;
		}

		.travel-field {
			font-size: 24rpx;
			color: #666;
		}

		.travel-dates {
			font-size: 24rpx;
			color: #FFC300;
		}
	}
}

.tour-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	line-height: 1.4;
	margin-bottom: 20rpx;
}


/* 联系人信息卡片样式 */
.contact-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.contact-header {
	margin-bottom: 20rpx;
}

.contact-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	display: flex;
	align-items: center;

	.contact-title-more {
		font-size: 24rpx;
		color: #666;
		margin-left: 10rpx;
		font-weight: normal;
	}
}

.contact-content {
	.contact-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;

		&:last-child {
			border-bottom: none;
		}
	}

	.contact-label {
		width: 140rpx;
		font-size: 28rpx;
		color: #333333;
	}

	.contact-input {
		flex: 1;
		border: none;
		background: transparent;
		font-size: 28rpx;
		color: #333333;
		padding: 0;
		height: auto;

		&:focus {
			border: none;
			outline: none;
		}
	}
}

/* 备注卡片样式 */
.remark-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.remark-header {
	margin-bottom: 20rpx;
}

.remark-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.remark-content {
	position: relative;
	overflow: hidden;
}

.remark-input {
	width: 100%;
	min-height: 120rpx;
	border-radius: 12rpx;
	padding: 20rpx;
	font-size: 28rpx;
	color: #333333;
	background-color: #f5f7fa;
	line-height: 1.5;
}

.remark-input:focus {
	border-color: #f8f8f8;
}

.remark-count {
	position: absolute;
	bottom: 10rpx;
	right: 20rpx;
	font-size: 24rpx;
	color: #999999;
}

/* 出行人信息卡片样式 */
.traveler-info-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.info-header {
	margin-bottom: 30rpx;
}

.info-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 15rpx;
}

.info-instruction {
	font-size: 26rpx;
	color: #666666;
	margin-bottom: 15rpx;
}

.invite-link {
	font-size: 26rpx;
	color: #FFC300;
	text-align: right;
}

/* 出行人选择区域 */
.traveler-selection {
	margin-bottom: 30rpx;
}

.traveler-cards {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.traveler-card {
	height: 70rpx;
	border-radius: 8rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	background-color: #F5F5F5;
	position: relative;
}

// f8f8f8
.traveler-card.selected {
	border-color: #FFC300;
	background-color: #FFC300;

	.traveler-name {
		color: #333;
	}
}

.traveler-name {
	font-size: 26rpx;
	color: #666;
	margin-bottom: 5rpx;
	font-weight: 500;
}

.traveler-type {
	font-size: 22rpx;
	color: #999999;
	position: absolute;
	top: 0rpx;
	left: 0rpx;
	background-color: #ebeef4;
	padding: 2rpx 8rpx;
	border-radius: 4rpx;
}

.add-card {
	background-color: #f5f5f5;
}

.add-text {
	font-size: 26rpx;
	color: #FFC300;
}

/* 出行人详细信息 */
.traveler-details {


	.traveler-detail-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.traveler-detail-item:last-child {
		border-bottom: none;
	}

	.detail-left {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.remove-btn {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background-color: #f5f5f5;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #999999;
		margin-right: 20rpx;
	}

	.traveler-info {
		flex: 1;
	}

	.detail-name {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.detail-name .traveler-name {
		font-size: 28rpx;
		color: #333333;
		font-weight: 500;
		margin-bottom: 0;
	}

	.traveler-tag {
		font-size: 22rpx;
		color: #999999;
		background-color: #f5f5f5;
		padding: 4rpx 12rpx;
		border-radius: 12rpx;
		margin-left: 15rpx;
	}

	.id-info {
		font-size: 26rpx;
		color: #666666;
	}
}

.edit-btn {
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	color: #FFC300;
}

/* 房间选择区域样式 */
.room-selection-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.room-selection-card:empty {
	display: none;
}

.room-selection {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.room-info {
	display: flex;
	align-items: center;
}

.room-label {
	font-size: 28rpx;
	color: #666666;
	margin-right: 20rpx;
}

.room-count-control {
	display: flex;
	align-items: center;
}

.room-price-info {
	display: flex;
	align-items: center;
}

.price-label {
	font-size: 28rpx;
	color: #666666;
}

.price-value {
	font-size: 24rpx;
	color: #ff6b35;
	font-weight: bold;
}

/* 酒店选择区域样式 */
.hotel-selection-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.hotel-selection {
	display: flex;
	flex-direction: column;
}

.hotel-options {
	display: flex;
	flex-direction: column;
}

.hotel-option {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	border: 2rpx solid #f0f0f0;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	transition: all 0.3s ease;
}

.hotel-option:last-child {
	margin-bottom: 0;
}

.hotel-option.selected {
	border-color: #FFC300;
	background-color: #fff9e6;
}

.hotel-option.selected .hotel-name {
	color: #FFC300;
}

.hotel-option.selected .hotel-price {
	color: #FFC300;
}

.hotel-info {
	flex: 1;
}

.hotel-name {
	font-size: 28rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 5rpx;
}

.hotel-description {
	font-size: 24rpx;
	color: #666666;
}

.hotel-price {
	font-size: 28rpx;
	color: #ff6b35;
	font-weight: bold;
}

/* 出行人表单弹窗样式 */
.traveler-form {
	height: 60vh;
	display: flex;
	flex-direction: column;
}

.form-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.close-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 60rpx;
	color: #999999;
}

.form-content {
	flex: 1;
	padding: 30rpx;
}

.form-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-item:last-child {
	border-bottom: none;
}

.form-label {
	font-size: 28rpx;
	color: #666666;
	font-weight: normal;
}

.form-input {
	flex: 1;
	text-align: right;
	border: none;
	background: transparent;
	font-size: 28rpx;
	color: #333333;
	padding: 0;
	height: auto;
}

.form-input:focus {
	border: none;
	outline: none;
}

.form-value {
	flex: 1;
	text-align: right;
	font-size: 28rpx;
	color: #333333;
}

.form-actions {
	width: 100%;
	display: flex;
	gap: 20rpx;
	padding: 30rpx;
	border-top: 1rpx solid #f0f0f0;
	padding-bottom: 60rpx;
}

.form-actions .btn {
	flex: 1;
}

/* 底部固定栏样式 */
.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 220rpx;
	background-color: #f8f9fa;
	border-top: 1rpx solid #e0e0e0;
	padding-bottom: 40rpx;
	z-index: 999;

	.submit-btn-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
	}


	.login-footer {
		width: 100%;
		font-size: 24rpx;
		font-weight: normal;
		color: #999;
		display: flex;
		justify-content: flex-end;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		padding-right: 20rpx;

		.publish-icon {
			width: 32rpx;
			height: 32rpx;
			margin-right: 10rpx;
		}
	}
}

.price-summary {
	display: flex;
	flex-direction: column;
}

.total-price {
	display: flex;
	align-items: center;
}

.currency {
	font-size: 32rpx;
	color: #ff6b35;
	font-weight: bold;
}

.amount {
	font-size: 48rpx;
	color: #ff6b35;
	font-weight: bold;
	margin-right: 15rpx;
}

.discount-tag {
	background-color: #fff2e6;
	border: 1rpx solid #ff6b35;
	border-radius: 8rpx;
	padding: 4rpx 12rpx;
	font-size: 22rpx;
	color: #ff6b35;
}

.price-label {
	font-size: 24rpx;
	color: #999999;
	text-align: center;
}

.action-buttons {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.detail-btn {
	display: flex;
	align-items: center;
	font-size: 28rpx;
	color: #FFC300;
	padding: 10rpx 15rpx;
}

.chevron {
	font-size: 20rpx;
	margin-left: 8rpx;
}

.service-btn {
	display: flex;
	align-items: center;
	background-color: #FFC300;
	color: #ffffff;
	padding: 15rpx 20rpx;
	border-radius: 25rpx;
	font-size: 26rpx;
	box-shadow: 0 4rpx 8rpx rgba(0, 122, 255, 0.3);
}

.service-avatar {
	width: 32rpx;
	height: 32rpx;
	border-radius: 50%;
	margin-right: 8rpx;
}

.submit-btn {
	font-size: 28rpx;
	font-weight: bold;
}

/* 购买须知弹窗样式 */
.notice-popup {
	display: flex;
	flex-direction: column;


	.notice-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.notice-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}

	.notice-content {
		width: 100%;
		height: 70vh;
		overflow: hidden;
		box-sizing: border-box;

		.notice-content-item {
			padding: 30rpx;
		}
	}

	.notice-item {
		margin-bottom: 30rpx;
	}

	.notice-item:last-child {
		margin-bottom: 0;
	}

	.notice-label {
		font-size: 28rpx;
		color: #333333;
		font-weight: bold;
		margin-bottom: 15rpx;
	}

	.notice-text {
		font-size: 26rpx;
		color: #666666;
		line-height: 1.5;
	}
}

/* 价格明细弹窗样式 */
.price-detail {
	height: 60vh;
	display: flex;
	flex-direction: column;
}

.detail-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.detail-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.detail-content {
	flex: 1;
	padding: 30rpx;
}

.detail-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
}

.detail-label {
	font-size: 28rpx;
	color: #666666;
}

.detail-value {
	font-size: 28rpx;
	color: #333333;
}

.detail-divider {
	height: 1rpx;
	background-color: #f0f0f0;
	margin: 20rpx 0;
}

.detail-item.total .detail-value {
	font-weight: bold;
	color: #333333;
}

.detail-item.discount .detail-value {
	color: #ff6b35;
}

.detail-item.final {
	border-top: 1rpx solid #f0f0f0;
	padding-top: 20rpx;
	margin-top: 20rpx;
}

.detail-item.final .detail-label {
	font-weight: bold;
	color: #333333;
}

.detail-item.final .detail-value {
	font-size: 32rpx;
	font-weight: bold;
	color: #ff6b35;
}

.participant-info {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.participant-count,
.room-count {
	font-size: 28rpx;
	color: #333333;
}

.divider {
	width: 2rpx;
	height: 24rpx;
	background-color: #e0e0e0;
	margin: 0 20rpx;
}

.cancellation-policy {
	font-size: 28rpx;
	color: #FFC300;
	line-height: 1.4;
}
</style>
